package edu.hznu.retroSnakerPlanServer.runner;

import edu.hznu.retroSnakerPlanServer.entity.GameContext;
import edu.hznu.retroSnakerPlanServer.entity.Player;
import edu.hznu.retroSnakerPlanServer.factory.GameContextFactory;
import edu.hznu.retroSnakerPlanServer.service.PlayerService;
import edu.hznu.retroSnakerPlanServer.service.imp.PlayerServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * create by Cliven on 2018-06-11 7:38
 * 玩家维护线程，该线程用于维护玩家超时时候自动释放玩家资源
 */
public class PlayerMaintenaceRunner implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(PlayerMaintenaceRunner.class);

    private GameContext ctx;
    private PlayerServiceImpl playerService;

    public PlayerMaintenaceRunner() {
        ctx = GameContextFactory.generate();
        playerService = new PlayerServiceImpl(ctx);
    }


    @Override
    public void run() {
        Long dt;
        Player removedPlayer;
        while (true) {
            try {

                // 获取超从超时结束的时间
                for (int id = 1; id <= ctx.getMaxPlayerNumber(); id++) {

                    Player playerItem = playerService.findById(id);
                    if (playerItem != null) {
                        dt = System.currentTimeMillis() - playerItem.getLastUpdateTime();

                        // 如果上次更新的时间超过了当前限制超时时间
                        if (dt > ctx.getPlayerConnectionTimeOutMillsec()) {
                            removedPlayer = playerService.remove(id);
                            log.info("Player connection time out remove,{} ", removedPlayer.toString());
                        }
                    }
                }

            } catch (RuntimeException e) {
                log.error("Player MaintenaceRunner get error:", e);
            }
        }
    }
}
